package com.fq.rpc.task;

import com.fq.rpc.domain.InterfaceWrapper;
import com.fq.rpc.util.Hessian2Serializer;
import com.fq.rpc.util.ReaderUtil;
import com.fq.rpc.util.ServiceImplMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.Socket;

/**
 * @author jifang
 * @since 16/8/4 上午11:05.
 */
public class ProducerInvokeTask implements Runnable {

    private static final Logger LOGGER = LoggerFactory.getLogger(ProducerInvokeTask.class);

    private Socket client;

    public ProducerInvokeTask(Socket client) {
        this.client = client;
    }

    @Override
    public void run() {
        try (InputStream in = client.getInputStream();
             OutputStream out = client.getOutputStream()) {

            // 读出数据 反序列化
            byte[] bytes = ReaderUtil.toByteArray(in);
            InterfaceWrapper wrapper = Hessian2Serializer.deserialize(bytes);

            // 执行方法调用
            Object service = ServiceImplMap.get(wrapper.getInter());
            Method method = service.getClass().getMethod(wrapper.getMethodName(), wrapper.getParamTypes());
            Object result = method.invoke(service, wrapper.getArguments());

            // 序列化 写入数据
            bytes = Hessian2Serializer.serialize(result);
            out.write(bytes);
        } catch (IOException | NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
            LOGGER.error("Producer Invoke Task Error: ", e);
        }
    }
}
